<template>
	<view>
		<js-error mode="bottom" ref="jsError" @update:errorClose="onErrorClose"></js-error>
		<u-sticky class="u-sticky">
			<view class="cu-bar search" style="padding: 10px">
				<u-search style="flex: 1;" v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描"
					:show-action="false" @search="confirmInput"></u-search>
				<view style="margin-left: 10px; display: flex; flex-direction: column">
					<u-icon @click="search" name="scan" size="50"></u-icon>
				</view>
			</view>
		</u-sticky>
		<!-- @scrolltoupper="refresherrefresh" @scrolltolower="loadMore" @refresherrefresh="refresherrefresh" -->
		<scroll-view scroll-y="true"  :refresher-enabled="true" :scrolltolower-enabled="true"
			:refresher-triggered="triggered" 
			class="scroll-view-class" :style="{ height: computedScrollViewHeight }">
			<view class="scroll-content" ref="scrollContent" style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        ">
				<view v-for="(item,index) in list" class="cu-item shadow " style="position: relative;" :key="item.barCode">
					<view class="cu-form-group" style="display: flex;justify-content: space-between;">
						<view
							style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;min-width: 40px;text-align: center;font-style: italic;font-weight: bold">
							{{ index + 1 }}
						</view>
						<view class="">
							<!-- v-if="model.basWare.bwhpos == '1' || model.basInv.binvbatch == '1'" -->
							<text style="font-size: 35px;" class="cuIcon-deletefill text-sl text-red"
								@tap="delDetail(item.barCode)"></text>
						</view>
					</view>
					
					
					<view class="cu-form-group">
						<view style="flex: 1;">{{ item.barCode }}</view>
					</view>


				</view>

				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 80vh;"></u-empty>
			</view>
		</scroll-view>
		<!--  -->
		<view class="btn-group cu-bar foot">
			<button class="cu-btn bg-green shadow-blur" @tap="submit()">
				确定
			</button>
		</view>
		<movable-area class="movable-area1">
			<movable-view class="movable-view" :x="x" :y="y" direction="all">
				<view @click="backInv" class="custom-style" style="width: 90px; height: 70px; color: #fff; border-radius: 10rpx;">
					<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
						<text class="cuIcon-camera text-xxls text-blue"></text>
						<view class="text-blue">条码识别</view>
					</view>
				</view>
				<!-- <button size="mini" >
					
				</button> -->
			</movable-view>
		</movable-area>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				type: 'text',
				inputStyle: {
					fontSize: '34rpx'
				},
				filterIcon: "/static/image/filter.png",
				background: {
					backgroundColor: '#3E97B0',
				},
				list: [],
				itemContent: {},
				query: {
					pageNo: 1,
					pageSize: 5,
					// orderBy: "a.create_date desc",
				},
				scrollViewHeight: 0,
				headerHeight: 0,
				triggered: false,
				loadStatus: "loadmore",
				xiangNums : 0,
				guanNums: 0,
				gcodes:'',
				xcodes:'',
				cacheData:{},
				focus:true,
				barCode:'',
				cusCode:'',
				bizKey:'',
				x: 640, //x坐标
				y: 700, //y坐标

			};
		},
		onLoad() {
			var _this = this;
			const eventChannel = this.getOpenerEventChannel();
		    eventChannel.on('initfilter',function(info){
				_this.list = info.data;
				_this.xiangNums = info.xiangNums;
			});
		},
		mounted() {
			this.calculateScrollViewHeight();
		},
		computed: {
			computedScrollViewHeight() {
				return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
			},
		},
		methods: {
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.focus = true;
				}, 500);
			},
			search() {
				var _that = this;
				_that.focus = false
				// #ifdef APP-PLUS
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
				mpaasScanModule.mpaasScan({
					// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
					'scanType': ['qrCode', 'barCode'],
					// 是否隐藏相册，默认false不隐藏
					'hideAlbum': false,
					//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
					'language': 'en',
					//相册选择照片识别错误提示(ios)
					'failedMsg': '未识别到二维码，请重试',
					//Android支持全屏需要设置此参数
					'screenType': 'full'
				},
					async (ret) => {
						console.log('ret', ret)
						if (ret.resp_message == 'success') {
							_that.barCode = ret.resp_result;
							
							await _that.getDeleteCache(ret.resp_result)
						}
					})
				// #endif
				// #ifdef H5 || MP-WEIXIN || MP-QQ 
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					success: async (res) => {
						_that.barCode = res.result;
			
						await _that.getDeleteCache(res.result)
					}
				})
				// #endif
			},
			async confirmInput() {
				this.focus = false
				console.log(this.barCode, 'barCode')
				await this.getDeleteCache(this.barCode)
			},
			delDetail(item) {
				let that = this
				uni.showModal({
					title: '删除提示',
					content: '是否删除此记录？',
					confirmColor: '#F54E40',
					success: async (res) => {
						if (!res.confirm) {
							return false;
						}
						await this.getDeleteCache(item)
						
					}
				})
			},
		
			
			
		    async getDeleteCache(barCode){
				var _this = this;
				var list = _this.list;
				

				// const { bizKey } = list[itemIndex];
				const bizKey = this.bizKey
				
				const response = await this.$u.api.zgz.deleteCache({ bizKey, barCode });

				const itemIndex = list.findIndex(item => item.barCode === response.data.barCode);

				if (itemIndex === -1) {
					setTimeout(()=>{
						this.barCode = '';
						this.makeSound("bcz");
					},500)
					this.$refs.jsError.showError('', '当前码不存在', 'error');
					if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
						this.handleFocus()
					}
					return;
				}
				if (response.result === 'true') {
					if(response.data.boxType === _this.vuex_config.xiangPrefix){
								// 数量加1
						_this.xiangNums--
						const xcodesArray = _this.xcodes.split(',');
						const FilterXcodesArray = xcodesArray.filter(item => item !== barCode)
		
						_this.xcodes = FilterXcodesArray.join(',')
		
					}else if(response.data.boxType === _this.vuex_config.guanPrefix){
						// 数量加1
						_this.guanNums--
						const xcodesArray = _this.gcodes.split(',');
						const FilterXcodesArray = xcodesArray.filter(item => item !== barCode)
						_this.gcodes = FilterXcodesArray.join(',')
					}
					list.splice(itemIndex,1);
					setTimeout(()=>{
						this.barCode = '';
						this.makeSound("cg");
					},500)
				} else {
					setTimeout(()=>{
						this.barCode = '';
						this.makeSound("sb");
					},500)
					this.$refs.jsError.showError('', response.message, 'error');
				}
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					this.handleFocus()
				}
				_this.$forceUpdate()
			},


			submit(){
				setTimeout(() => {
				    const eventChannel = this.getOpenerEventChannel();
					this.cacheData = {
						data:this.list,
						xiangNums:this.xiangNums,
						guanNums:this.guanNums,
						gcodes:this.gcodes,
						xcodes:this.xcodes,
					}
				    eventChannel.emit('Filter', this.cacheData);
			    }, 300);
				uni.navigateBack();
			},


			async calculateScrollViewHeight() {
				try {
					this.headerHeight = 52
					// 计算tabBar高度
					if (this.flag) {
						this.tabBarHeight = 60; // 假设tabbar高度为50px，实际应根据实际情况获取
					} else {
						this.tabBarHeight = 0;
					}
					// 获取屏幕高度
					const systemInfo = uni.getSystemInfoSync();
					const screenHeight = systemInfo.windowHeight;
					// 计算scroll-view高度
					this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
				} catch (error) {
					console.error('Error while calculating ScrollView height:', error);
				}
			},
			makeSound(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
				});
				Audio.onPause(function () {
					console.log('end');
					Audio.destroy();
				});
			},
			onErrorClose(result) {
				console.log('result',result)
			//   获取focus 焦点
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
						this.focus = true;
					}
					
				}, 100);
			 
			},
			backInv(){
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP){
					this.search()
				}else if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					this.handleFocus()
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 100rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透
		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件
			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
	.cu-bar {
		min-height: 60px;
	}
	.text-xxls{
		font-size:60rpx;
	}
	.cu-btn {
		font-size: 16px;
		height: 40px;
	}

	.foot {
		background: #fff;
	}

	.cu-item {
		flex-wrap: wrap;
		padding: 8px 15px !important;
	}

	.title {
		width: 230rpx;
	}

	.cu-modal-slot {
		margin: 42rpx 32rpx 20rpx 32rpx;
		height: 100vh;
		position: relative;
	}

	.cu-modal-header {
		font-size: 38rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		text-align: left;
		font-weight: 500;
	}

	.button {
		font-size: 32rpx;
		color: #666666;
		line-height: 40rpx;
		padding: 12rpx 40rpx;
		margin-bottom: 20rpx;
		background: #e2e2e2;
		border-radius: 180rpx;
	}

	.button:hover {
		background: #3e97b0;
		color: #ffffff;
	}

	.cu-modal-search-title {
		margin: 32rpx 0rpx 20rpx 0rpx;
		text-align: left;
		font-size: 32rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.cu-dialog {
		background: #ffffff;
	}

	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;

		.cu-btn {
			width: 50%;
		}
	}

	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
	.text-sl{
		font-size: 40px !important;
	}
</style>